package com.cskaoyan.gateway.controller.user;
/*
 * @ClassName : RegisterController
 * @Description :
 * @Author : Jason
 * @Date : 2021/7/21 08:28:01
 * @Version : V1.0
 */

import com.alibaba.fastjson.JSON;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IRegisterService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class RegisterController {

    @Reference(timeout = 3000,check =  false)
    private IKaptchaService iKaptchaService;

    @Reference(timeout = 15000,check = false)
    private IRegisterService iRegisterService;

    /**
     * 注册
     * @param map map类型请求参数
     * @param httpServletRequest 请求参数
     * @return ResponseData
     */
    @PostMapping("/register")
    @Anoymous
    public ResponseData register(@RequestBody Map<String,String> map, HttpServletRequest httpServletRequest){

        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        String email = map.get("email");

        //验证验证码
        KaptchaCodeResponse response = validKaptchaCode(captcha,httpServletRequest);
        String code = response.getCode();

        if(!code.equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }

        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setEmail(email);
        userRegisterRequest.setUserName(userName);
        userRegisterRequest.setUserPwd(userPwd);

        UserRegisterResponse register = iRegisterService.register(userRegisterRequest);
        if(register.getCode().equals(SysRetCodeConstants.SUCCESS.getCode()))
        {
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(register.getMsg());
    }

    /**
     * 登录
     * @param map 传入的map类型参数
     * @param request 请求参数
     * @param response 请求参数
     * @return ResponseData
     */
    @PostMapping("/login")
    @Anoymous
    public ResponseData login(@RequestBody Map<String,String> map, HttpServletRequest request, HttpServletResponse response){

        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");

        //验证验证码
        KaptchaCodeResponse kaptchaCodeResponse = validKaptchaCode(captcha,request);
        String code = kaptchaCodeResponse.getCode();
        if(!code.equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }

        //验证账户和密码
        UserLoginRequest userLoginRequest = new UserLoginRequest();
        userLoginRequest.setPassword(userPwd);
        userLoginRequest.setUserName(userName);

        //登录
        UserLoginResponse userLoginResponse = iRegisterService.login(userLoginRequest);

        //如果可以登录，将返回值放在token中；并放在cookie中，并返回登录成功的状态
        if(userLoginResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            Cookie cookie = CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN,userLoginResponse.getToken(),"/",3600);
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            return new ResponseUtil<>().setData(userLoginResponse);
        }

        return new  ResponseUtil<>().setErrorMsg(userLoginResponse.getMsg());
    }

    /**
     * 检查登录状态
     * @param request 请求参数
     * @param response 请求参数
     * @return ResponseData
     */
    @GetMapping("/login")
    public ResponseData checkLogin(HttpServletRequest request,HttpServletResponse response)
    {
        String userInfo = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        if(userInfo.isEmpty()){
            return new ResponseUtil<>().setErrorMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
        }
        Map map = JSON.parseObject(userInfo);
        UserLoginCheckResponse loginCheckResponse = new UserLoginCheckResponse();
        loginCheckResponse.setUid((Integer) map.get("uid"));
        loginCheckResponse.setFile((String) map.get("file"));;
        loginCheckResponse.setUsername((String) map.get("username"));
        return  new ResponseUtil<>().setData(loginCheckResponse);
    }

    /**
     * 退出登录
     * @param request 请求参数
     * @param response 请求参数
     * @return ResponseData
     */
    @GetMapping("/loginOut")
    public ResponseData logout(HttpServletRequest request,HttpServletResponse response)
    {
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        return new ResponseUtil<>().setData(null);
    }

    /**
     * 激活用户注册的方法
     * @param uid 用户密码
     * @param username 用户姓名
     * @return
     */
    @GetMapping("/verify")
    @Anoymous
    public ResponseData verify (String uid, String username){
        UserVerifyResponse userVerifyResponse = iRegisterService.verify(uid,username);
        return new ResponseUtil<>().setData(userVerifyResponse);
    }
    /**
     * 验证验证码的方法
     * @param captcha 验证码
     * @param httpServletRequest 请求参数
     * @return KaptchaCodeResponse
     */
    private KaptchaCodeResponse validKaptchaCode(String captcha,HttpServletRequest httpServletRequest){
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String kaptcha_uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(kaptcha_uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse response = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        return response;
    }
}
